package com.csx.ops.service.node;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.thoughtworks.xstream.annotations.XStreamAsAttribute;
import com.thoughtworks.xstream.annotations.XStreamImplicit;
import com.thoughtworks.xstream.annotations.XStreamOmitField;
import com.xxl.job.core.util.DateUtil;
import com.yh.csx.bsf.core.util.JsonUtils;
import com.yh.csx.bsf.core.util.StringUtils;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
import lombok.var;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

public class BaseNode {

    @Getter @Setter
    @XStreamAsAttribute
    private String text;

    @Getter @Setter
    @XStreamAsAttribute
    private String next;

    /**
     * x y位置 示范：100 200
     */
    @Getter @Setter
    @XStreamAsAttribute
    private String location;

    @XStreamOmitField
    @Setter
    private String type;


    /**
     * 当前操作类型，是正常发布，还是回滚
     */
    @Getter @Setter
    private String operateType;

    public String getType(){
        if(!StringUtils.isEmpty(type)){
            return type;
        }
        return this.getClass().getSimpleName().replace("Node","").toLowerCase();
    }


    @Getter
    @Setter
    @XStreamOmitField
    @JsonIgnore
    StateEngine engine;
    public BaseNode(){};
    public BaseNode(StateEngine engine){
        this.engine=engine;
    }

    public void flow(){
        String title="未知标题";
        if("normal".equals(operateType)){
            title="正常发布流程";
        }
        if("rollback".equals(operateType)){
            title="回滚发布流程";
        }
        writeLog(title+":【"+this.text+"】节点于"+ printTime()+"开始执行.....................");
        this.exec();
        this.goNextNode();
        writeLog(title+":【"+this.text+"】节点于"+ printTime()+"执行完毕.....................");
    }

    protected String printTime(){
        return DateUtil.format(new Date(),"yyyy-MM-dd HH:mm:ss");
    }

    public void exec(){

    }

    public void goNextNode(){
        if(StringUtils.isEmpty(next)){
            throw new StateException("当前节点"+this.getText()+"无下一个节点");
        }
        goNextNode(next);
    }

    protected void goNextNode(String text){
        var nextNode = findNode(text);
        if(nextNode == null){
            throw new StateException("找不到下一个节点:"+text);
        }
        nextNode.flow();
    }

    public List<BaseNode> getLastNodes(){
        return null;
    }

    public BaseNode findNode(String text){
       var find = this.engine.getNodes().parallelStream().filter(c->c.text.equals(text)).findFirst();
       return find.isPresent()? find.get():null;
    }

    protected void writeLog(String content){
        engine.writeLog(content+"\r\n");
    }

    protected void printParam(Object... params){
        writeLog("[参数]"+ JsonUtils.serialize(new Object[]{params}));
    }
}
